/**
 * JAVACC DEMO 1.0
 */
package com.apache.ius;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.service.impl.redis.JedisSsoUtil;
import com.apache.cache.util.Validator;
import com.apache.client.InfoReleaseCoreCleint;
import com.apache.client.common.ScheduledExecutor;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.constant.SystemTools;
import com.apache.database.datasource.ConnctionData;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.info.entity.PubMetadata;
import com.apache.info.util.MessageUtil;
import com.apache.ius.able.LogWriteRunnable;
import com.apache.ius.impl.MaxContentPorxyPluginImpl;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusSqlPorxyPlugin;
import com.apache.ius.plugin.MaxContentPorxyPlugin;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.apache.tools.UUIDUtil;
import com.apache.uct.common.ToolsUtil;

import net.sf.json.JSONObject;

/**
 * description:
 *
 * @author Administrator 创建时间：2016-10-18
 */
public class DymicSqlSuper {

	protected IusSqlPorxyPlugin iusSqlPorxyPlugin;

	public void exeCustomPlugin(ParamsVo vo, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		String keys = String.valueOf(vo.getParams("sqlKeyId"));
		if (Validator.isNotNull(keys)) {
			String beforMethodKey = String.valueOf(vo.getParams("beforMethodKey"));
			if (Validator.isNull(beforMethodKey)) {
				return;
			}
			vo.setMethodKey("beforMethodKey");
			map = (Map) getPlugin().doInvoke(vo);
			vo.setParams("beforMethodKey", "");
			vo.setParams("sqlKeyId", "");
		} else {
			if ("befor".equals(type)) {
				String beforMethodKey = String.valueOf(vo.getParams("beforMethodKey"));
				if (Validator.isNull(beforMethodKey))
					return;
				vo.setMethodKey("beforMethodKey");
				CustomMethodPlugin befor = CustomMethodFactory.getInstance().getPluginByKey(beforMethodKey);
				if (!Validator.isEmpty(befor)) {
					map = (Map) befor.beforeInvoke(vo.getParams());
					vo.setParams("beforMethodKey", "");
				}
			}
		}
		if (!Validator.isEmpty(map)) {
			for (String key : map.keySet()) {
				vo.setParams(key, map.get(key));
			}
		}
	}

	public void exeCustomPluginForAfter(ParamsVo vo, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		String keys = String.valueOf(vo.getParams("sqlKeyId"));
		if (Validator.isNotNull(keys)) {
			String afterMethodKey = String.valueOf(vo.getParams("afterMethodKey"));
			if (Validator.isNull(afterMethodKey)) {
				return;
			} else {
				vo.setMethodKey("afterMethodKey");
			}
			vo.setParams("sqlKeyId", afterMethodKey);
			map = (Map) getPlugin().doInvoke(vo);
			vo.setParams("afterMethodKey", "");
			vo.setParams("sqlKeyId", "");
		} else {
			if ("after".equals(type)) {
				String afterMethodKey = String.valueOf(vo.getParams("afterMethodKey"));
				if (Validator.isNull(afterMethodKey))
					return;
				vo.setMethodKey("afterMethodKey");
				CustomMethodPlugin after = CustomMethodFactory.getInstance().getPluginByKey(afterMethodKey);
				if (!Validator.isEmpty(after)) {
					map = (Map) after.afterInvoke(vo.getParams());
				}
				vo.setParams("afterMethodKey", "");
			}
		}
		if (!Validator.isEmpty(map) && !map.isEmpty()) {
			for (String key : map.keySet()) {
				vo.setParams(key, map.get(key));
			}
		}
	}

	protected String dymicSql(String exeType, ParamsVo vo, String primaryKeyId, String attrStr, String modelType,
			Map<String, String> params, String tableName) {
		if (exeType.startsWith("i_")) {//插入语句
			vo.setParams("rulePrimaryKey", modelType);
			return getInsertSqlStr(params, attrStr, tableName, primaryKeyId, vo);
		} else if (exeType.startsWith("ib_")) {//插入语句
			vo.setParams("rulePrimaryKey", modelType);
			return getInsertBatchSqlStr(params, attrStr, tableName, primaryKeyId, vo);
		} else if (exeType.startsWith("u_")) {//修改语句
			vo.setParams("rulePrimaryKey", modelType);
			return getUpdateSqlStr(params, attrStr, tableName, primaryKeyId, vo);
		} else if (exeType.startsWith("ub_")) {//批量修改语句
			vo.setParams("rulePrimaryKey", modelType);
			return getUpdateBatchSqlStr(params, attrStr, tableName, primaryKeyId, vo);
		} else if (exeType.startsWith("d_")) {
			vo.setParams("rulePrimaryKey", modelType);
			return getDealSqlStr(params, attrStr, tableName, vo, primaryKeyId);
		} else if (exeType.startsWith("s_")) {
			return getSelectSqlStr(params, attrStr, tableName, vo, primaryKeyId);
		}
		return "";
	}

	/**
	 * description:  拼动态原生的修改语句
	 */
	public String getUpdateSqlStr(Map<String, String> params, String attrStr, String tableName, String primaryKeyId,
			ParamsVo paramVo) {
		if (Validator.isEmpty(params) || params.size() <= 0)
			return "";
		StringBuilder sb2 = new StringBuilder("");
		StringBuilder sb3 = new StringBuilder("");
		boolean mark1 = false, mark2 = false;
		int i = 0;
		String rules = String.valueOf(paramVo.getParams("exe_rules"));
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));
		String idValue = "";
		String dataSource = String.valueOf(paramVo.getParams("datasource"));
		String fsKey = "";
		if (attrStr.indexOf("fsId") != -1) {
			MaxContentPorxyPlugin plugin = MaxContentPorxyPluginImpl.getInstance();
			if (StrUtil.isNotNull(params.get("cacheContent"))) {//文本内容插入
				fsKey = String.valueOf(plugin.saveContent(StrUtil.doNull(params.get("fsId"), ""), params));
			} else if (StrUtil.isNotNull(params.get("fsId"))) {
				JSONObject jb = JSONObject.fromObject(params);
				jb.remove("fsId");
				params.put("cacheContent", jb.toString());
				if (params.get("fsId").equalsIgnoreCase("fsId") || params.get("fsId").startsWith("cache_")) {
					//
				} else {
					params.put("dbType", "file");
				}
				fsKey = String.valueOf(plugin.saveContent(StrUtil.doNull(params.get("fsId"), ""), params));
				params.remove("cacheContent");
				params.remove("dbType");
			}
		}
		Map<String, String> tableMap = getTableMap(model, dataSource);
		for (String key : params.keySet()) {
			String val = params.get(key);
			if (attrStr.contains(key)) {//不带s_的情况
				if (val.startsWith("[")) {
					val = getValue(rules, model, key, val);
				} else {
					rules = rules.replaceAll("\\[" + model + "." + key + "\\]", val);
				}
				String cloumn = upperCharToUnderLine(key);
				if (primaryKeyId.indexOf(cloumn) != -1)//主键不能修改
					continue;
				if ("fsId".equalsIgnoreCase(key) && StrUtil.isNull(fsKey)) {
					continue;
				}
				sb2.append("," + sqlWhere(cloumn, val, tableMap.get(key), 3,""));//"," + cloumn + "='" + val + "'");
				mark1 = true;
			} else {
				/*String keyStr = key.substring(2);
				if (key.contains("wi_")) {
					keyStr = key.substring(3);
				}*/
				String clms[] = key.split("_");
				String keyStr = clms[clms.length-1];
				if (attrStr.contains(keyStr)) {
					if (val.startsWith("[")) {
						val = getValue(rules, model, keyStr, val);
					} else {
						rules = rules.replaceAll("\\[" + model + "." + keyStr + "\\]", val);
					}
					String cloumn = upperCharToUnderLine(keyStr);
					if (cloumn.equals(primaryKeyId)) {//唯一主键适用
						idValue = val;
					} else {
						if (primaryKeyId.indexOf(cloumn) != -1) {//联合主键
							setObjIds(paramVo, val, cloumn);
						}
					}
					if (key.startsWith("s_")) {//待修改的字段
						if ("is null".equalsIgnoreCase(val)) {
							sb2.append("," + cloumn + "=null");
						} else {
							sb2.append("," + sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 3,""));//"," + cloumn + "='" + val + "'");
						}
						mark1 = true;
					} else if (key.startsWith("w")) {//查询条件
						String cm = key.replace("_" + keyStr, "_");
						String whereSql = switchWhere(cloumn, "", keyStr, val, tableMap, cm, dataSource);
						if (i == 0) {
							whereSql = whereSql.substring(4);
							//sb3.append(sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 2,""));//cloumn + "='" + val + "'");
							i++;
						} else {
							//sb3.append(" and " + sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 2,""));//cloumn + "='" + val + "'");
						}
						sb3.append(whereSql);
						mark2 = true;
					} /*else if (key.startsWith("wi_")) {
						if (i == 0) {
							sb3.append(cloumn + " in(" + StrUtil.strArrayToStr(val.split(","), ",", "'") + ")");
							i++;
						} else {
							sb3.append(" and " + cloumn + " in(" + StrUtil.strArrayToStr(val.split(","), ",", "'") + ")");
						}
						mark2 = true;
					}*/
				}
			}
		}
		String iusWhere = String.valueOf(paramVo.getParams("ius_sql_where"));
		if(Validator.isNotNull(iusWhere)){//json拼的条件
			sb3.append(iusWhere);
			mark2 = true;
		}
		if (!mark1 || !mark2)
			return "";
		sb2.deleteCharAt(0);
		paramVo.setParams("exe_rules", rules);
		if (Validator.isNotNull(idValue)) {
			setObjIds(paramVo, idValue, primaryKeyId);
			params.put(toCamelNamed(primaryKeyId), idValue);
		}
		if (isSysParamManager(tableName, null, null)) {
			String key = params.get("formName") + "_" + params.get("pageName");
			try {
				Map iusParams = (Map)LoadCacheFactory.getInstance().getCacheManager("iusparamcache").getCacheObjectByKey(key);
				if(iusParams == null) {//当修改pageName或formName时
					if (Validator.isNotNull(idValue)) {
						String sqlStr = "select * from sys_param_manager where info_id='" + idValue + "'";
						iusParams = ConnctionData.getInstance().selectInfo(ConnctionData.getInstance().getConnection(dataSource),sqlStr);
						String key2 = iusParams.get("formName") + "_" + iusParams.get("pageName");
						LoadCacheFactory.getInstance().getCacheManager("iusparamcache").removeCacheObject(key2);
					} else {
						iusParams = new DataMap();
					}
					iusParams.put("page_name",params.get("pageName"));
					iusParams.put("formName",params.get("formName"));
				}
				iusParams.put("rules_name","is null".equalsIgnoreCase(params.get("s_rulesName"))?"":params.get("s_rulesName"));//插件组合
				iusParams.put("result_column","is null".equalsIgnoreCase(params.get("s_resultColumn"))?"":params.get("s_resultColumn"));//返回列
				iusParams.put("relation","is null".equalsIgnoreCase(params.get("s_relation"))?"":params.get("s_relation"));//关联关系
				iusParams.put("evel_name",StrUtil.isNull(params.get("evelName"))?"":params.get("evelName"));//拦截方式
				iusParams.put("model_types",StrUtil.isNull(params.get("modelTypes"))?"":params.get("modelTypes"));//增删改查接口
				iusParams.put("title",StrUtil.isNull(params.get("title"))?"":params.get("title"));//接口中文名称
				iusParams.put("user_owner",StrUtil.isNull(params.get("userOwner"))?"":params.get("userOwner"));//是否开启数据权限
				iusParams.put("check_column","is null".equalsIgnoreCase(params.get("s_checkColumn"))?"":params.get("s_checkColumn"));//需要判断唯一性的字段
				iusParams.put("cache_key","is null".equalsIgnoreCase(params.get("s_cacheKey"))?"":params.get("s_cacheKey"));//缓存KEY
				iusParams.put("result_name",StrUtil.isNull(params.get("resultName"))?"":params.get("resultName"));//返回类型
				iusParams.put("search_condition",StrUtil.isNull(params.get("searchCondition"))?"":params.get("searchCondition"));
				iusParams.put("pk_col",StrUtil.isNull(params.get("pkCol"))?"":params.get("pkCol"));
				setIusParamCache(key, iusParams);
			} catch (Exception e) {
				//
			}
		}
		saveLog(params, paramVo, "edit", tableName);//记录日志
		return "UPDATE " + tableName + " SET " + sb2.toString() + " where " + sb3.toString();
	}

	/**
	 * description:  拼动态原生的插入语句
	 */
	public String getInsertSqlStr(Map<String, String> params, String attrStr, String tableName, String primaryKeyId,
			ParamsVo paramVo) {
		if (Validator.isEmpty(params) || params.size() <= 0)
			return "";
		StringBuilder colName = new StringBuilder("");
		StringBuilder colValue = new StringBuilder("");
		String rules = String.valueOf(paramVo.getParams("exe_rules"));
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));
		if ("uct_user".equalsIgnoreCase(tableName)) {
			params.put("createTime", Long.toString(System.currentTimeMillis()));
			params.put("updateTime", Long.toString(System.currentTimeMillis()));
		}
		String fsKey = "";
		if (StrUtil.isNotNull(params.get("cacheContent"))) {//文本内容插入
			MaxContentPorxyPlugin plugin = MaxContentPorxyPluginImpl.getInstance();
			fsKey = String.valueOf(plugin.saveContent(StrUtil.doNull(params.get("fsId"), ""), params));
		}
		if (attrStr.indexOf("fsId") != -1) {
			MaxContentPorxyPlugin plugin = MaxContentPorxyPluginImpl.getInstance();
			if (StrUtil.isNotNull(params.get("cacheContent"))) {//文本内容插入
				fsKey = String.valueOf(plugin.saveContent(StrUtil.doNull(params.get("fsId"), ""), params));
			} else if (StrUtil.isNotNull(params.get("fsId"))) {
				JSONObject jb = JSONObject.fromObject(params);
				jb.remove("fsId");
				params.put("cacheContent", jb.toString());
				fsKey = String.valueOf(plugin.saveContent(StrUtil.doNull(params.get("fsId"), ""), params));
				params.remove("cacheContent");
			}
		}
		Map<String, String> tableMap = getTableMap(model, String.valueOf(paramVo.getParams("datasource")));
		boolean mark1 = false;
		String ifpkId = "";//是否有主键
		for (String key : params.keySet()) {
			String val = params.get(key);
			if (attrStr.contains(key)) {
				mark1 = true;
				String cloumn = upperCharToUnderLine(key);
				if (cloumn.equals(primaryKeyId) && Validator.isNull(val))
					continue;
				if (val.startsWith("[")) {
					val = getValue(rules, model, key, val);
					colValue.append("," + sqlWhere("", val, tableMap.get(key), 1,""));//",'" + val + "'");
				} else {
					if ("fsId".equalsIgnoreCase(key)) {////文本内容插入
						colValue.append(",'" + fsKey + "'");
					} else {
						colValue.append("," + sqlWhere("", val, tableMap.get(key), 1,""));//"," + val + "'");
						rules = rules.replaceAll("\\[" + model + "." + key + "\\]", val);
					}
				}
				if (cloumn.equals(primaryKeyId)) {//唯一主键适用
					ifpkId = val;
				} else {
					if (primaryKeyId.indexOf(cloumn) != -1) {//联合主键
						setObjIds(paramVo, val, cloumn);
					}
				}
				colName.append("," + cloumn);
			}
		}
		if (!mark1)
			return "";
		colName.deleteCharAt(0);
		colValue.deleteCharAt(0);

//		String id = UUIDUtil.generateId();
		String id = UUIDUtil.generateId();
		if (primaryKeyId.indexOf(",") == -1) {//唯一主键适用
			if (Validator.isNotNull(params.get(toCamelNamed(primaryKeyId))) || Validator.isNotNull(ifpkId)) {
				id = StrUtil.doNull(ifpkId, params.get(toCamelNamed(primaryKeyId)));
			}
			if (Validator.isNull(ifpkId)) {
				colName.append("," + primaryKeyId);
				colValue.append(",'" + id + "'");
			}
			rules = rules.replaceAll("\\[" + model + "." + toCamelNamed(primaryKeyId) + "\\]", id);

			setObjIds(paramVo, id, primaryKeyId);
			params.put(toCamelNamed(primaryKeyId), id);
		}
		paramVo.setParams("exe_rules", rules);
		isSysParamManager(tableName, params, null);
		saveLog(params, paramVo, "save", tableName);//记录日志
		return "insert into " + tableName + " (" + colName.toString() + " ) values ( " + colValue.toString() + ")";
	}

	/**
	 * description:  拼动态原生的插入语句（批量）
	 */
	public String getInsertBatchSqlStr(Map<String, String> params, String attrStr, String tableName,
			String primaryKeyId, ParamsVo paramVo) {
		if (Validator.isEmpty(params) || params.size() <= 0)
			return "";
		String rules = String.valueOf(paramVo.getParams("exe_rules"));
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));
		if ("uct_user".equalsIgnoreCase(tableName)) {
			params.put("createTime", Long.toString(System.currentTimeMillis()));
			params.put("updateTime", Long.toString(System.currentTimeMillis()));
		}
		boolean mark1 = false;
		boolean ifpkId = false;
		Map<String, String> tableMap = getTableMap(model, String.valueOf(paramVo.getParams("datasource")));
		boolean isCache = isSysParamManager(tableName, null, null);
		List<Map<String, String>> cacheList = new ArrayList<Map<String, String>>();
		String splitAttr = params.get("splitAttr");///用来表示分隔数据列;'-#-'分隔符
		if (StrUtil.isNull(splitAttr) || StrUtil.isNull(params.get(splitAttr))) {
			return "";
		}
		String splitValues[] = params.get(splitAttr).split("-#-");
		int count = splitValues.length;
		StringBuilder ids = new StringBuilder();
		StringBuilder inserts = new StringBuilder("");
		Map<String, String> pkIds = new HashMap<String, String>(1);
		for (int i = 0; i < count; i++) {
			Map<String, String> pmMap = null;
			if (isCache) {
				pmMap = new HashMap<String, String>();
			}
			StringBuilder colName = new StringBuilder("");
			StringBuilder colValue = new StringBuilder("");
			for (String key : params.keySet()) {
				String val = "";
				if (key.equalsIgnoreCase(splitAttr)) {
					val = splitValues[i];
					if ("_".equals(val)) {//处理空值时
						val = "";
					}
					if (StrUtil.isNull(val)){
						continue;
					}
				} else {
					val = params.get(key);
					if (val.indexOf("-#-") != -1) {
						String splitVals[] = val.split("-#-");
						if (splitVals.length - 1 < i) {
							val = "";
						} else {
							val = splitVals[i];
							if ("_".equals(val)) {//处理空值时
								val = "";
							}
						}
					}
				}
				if (attrStr.indexOf(key) != -1) {//符合徒插入字段
					mark1 = true;
					String cloumn = upperCharToUnderLine(key);//将类属性改成数据字段名
					if (val.startsWith("[")) {
						val = getValue(rules, model, key, val);//匹配值
					}
					if (cloumn.equals(primaryKeyId)) {//是否主键列
						ifpkId = true;
						val = StrUtil.doNull(val, UUIDUtil.generateId());
						ids.append("," + val);
					} else {//暂不支持联合主键批量插入
						if (primaryKeyId.indexOf(cloumn) != -1) {//联合主键
							pkIds.put(cloumn, StrUtil.doNull(pkIds.get(cloumn), "") + "," + val);
						}
					}
					colValue.append("," + sqlWhere(cloumn, val, tableMap.get(key), 1,""));//",'" + val + "'");
					colName.append("," + cloumn);
					if (isCache) {
						pmMap.put(key, val);
					}
				}
			}
			if (primaryKeyId.indexOf(",") == -1) {
				if (!ifpkId) {//不含主键，给主键生成值
					String id = UUIDUtil.generateId();
					colValue.append(",'" + id + "'");
					colName.append("," + primaryKeyId);
					ids.append("," + id);
					ifpkId = false;
				}
			}
			colName.deleteCharAt(0);
			colValue.deleteCharAt(0);
			inserts.append(";insert into " + tableName + " (" + colName.toString() + " ) values ( "
					+ colValue.toString() + ")");
			if (null != pmMap) {
				cacheList.add(pmMap);
			}
		}

		if (!mark1)
			return "";
		inserts.deleteCharAt(0);
		if (primaryKeyId.indexOf(",") == -1) {
			ids.deleteCharAt(0);
			setObjIds(paramVo, ids.toString(), primaryKeyId);
		} else {
			String str[] = primaryKeyId.split(",");
			for (int i = 0; i < str.length; i++) {
				setObjIds(paramVo, pkIds.get(str[i]).substring(1), str[i]);
			}
		}
		//saveLog(params, paramVo, "save", tableName);//记录日志
		if (isCache) {
			isSysParamManager(tableName, null, cacheList);
		}
		return inserts.toString();
	}

	/**
	 * description:  拼动态原生的插入语句（批量）
	 */
	public String getUpdateBatchSqlStr(Map<String, String> params, String attrStr, String tableName,
			String primaryKeyId, ParamsVo paramVo) {
		if (Validator.isEmpty(params) || params.size() <= 0)
			return "";
		String rules = String.valueOf(paramVo.getParams("exe_rules"));
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));
		if ("uct_user".equalsIgnoreCase(tableName)) {
			params.put("updateTime", Long.toString(System.currentTimeMillis()));
		}
		String dataSource = String.valueOf(paramVo.getParams("datasource"));
		Map<String, String> tableMap = getTableMap(model, dataSource);
		String splitAttr = params.get("splitAttr");///用来表示分隔数据列;'-#-'分隔符
		if (StrUtil.isNull(splitAttr) || StrUtil.isNull(params.get(splitAttr)))
			return "";
		String splitValues[] = params.get(splitAttr).split("-#-");
		int count = splitValues.length;
		StringBuilder ids = new StringBuilder();
		StringBuilder inserts = new StringBuilder("");
		Map<String, String> pkIds = new HashMap<String, String>(1);
		for (int i = 0; i < count; i++) {
			StringBuilder colName = new StringBuilder("");
			StringBuilder colValue = new StringBuilder("");
			boolean mark1 = false, mark2 = false;
			String idValue = "";
			int p = 0;
			for (String key : params.keySet()) {
				String val = "";
				if (key.equalsIgnoreCase(splitAttr)) {
					val = splitValues[i];
				} else {
					val = params.get(key);
					if (val.indexOf("-#-") != -1) {
						String splitVals[] = val.split("-#-");
						if (splitVals.length - 1 < i) {
							val = "";
						} else {
							val = splitVals[i];
							if ("_".equals(val)) {//处理空值时
								val = "";
							}
						}
					}
				}
				if (attrStr.contains(key)) {//不带s_的情况
					if (val.startsWith("[")) {
						val = getValue(rules, model, key, val);
					} else {
						rules = rules.replaceAll("\\[" + model + "." + key + "\\]", val);
					}
					String cloumn = upperCharToUnderLine(key);
					if (primaryKeyId.indexOf(cloumn) != -1)
						continue;
					colName.append("," + sqlWhere(cloumn, val, tableMap.get(key), 3,""));//"," + cloumn + "='" + val + "'");
					mark1 = true;
				} else {
					/*String keyStr = key.substring(2);
					if (key.contains("wi_")) {
						keyStr = key.substring(3);
					}*/
					String clms[] = key.split("_");
					String keyStr = clms[clms.length-1];
					if (attrStr.contains(keyStr)) {
						if (val.startsWith("[")) {
							val = getValue(rules, model, keyStr, val);
						} else {
							rules = rules.replaceAll("\\[" + model + "." + keyStr + "\\]", val);
						}
						String cloumn = upperCharToUnderLine(keyStr);
						if (cloumn.equalsIgnoreCase(primaryKeyId)) {
							idValue = val;
						} else {//暂不支持联合主键批量插入
							if (primaryKeyId.indexOf(cloumn) != -1) {//联合主键
								pkIds.put(cloumn, StrUtil.doNull(pkIds.get(cloumn), "") + "," + val);
							}
						}
						if (key.startsWith("s_")) {//待修改的字段
							if ("is null".equalsIgnoreCase(val)) {
								colName.append("," + cloumn + "=null");
							} else {
								colName.append("," + sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 3,""));//"," + cloumn + "='" + val + "'");
							}
							mark1 = true;
						} else if (key.startsWith("w")) {//查询条件
							String cm = key.replace("_" + keyStr, "_");
							String whereSql = switchWhere(cloumn, "", keyStr, val, tableMap, cm, dataSource);
							if (p == 0) {
								whereSql = whereSql.substring(4);
								//colValue.append(sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 2,""));//cloumn + "='" + val + "'");
								p++;
							} else {
								//colValue.append(" and " + sqlWhere(cloumn, val, tableMap.get(key.substring(2)), 2,""));
							}
							colValue.append(whereSql);
							mark2 = true;
						} /*else if (key.startsWith("wi_")) {
							if (p == 0) {
								colValue.append(cloumn + " in(" + StrUtil.strArrayToStr(val.split(","), ",", "'") + ")");
								p++;
							} else {
								colValue.append(" and " + cloumn + " in("+ StrUtil.strArrayToStr(val.split(","), ",", "'") + ")");
							}
							mark2 = true;
						}*/
					}
				}
			}
			if (!mark1 || !mark2)
				continue;
			if (Validator.isNotNull(idValue)) {
				ids.append("," + idValue);
			}
			colName.deleteCharAt(0);
			inserts.append(
					";UPDATE " + tableName + " SET " + colName.toString() + " where " + colValue.toString() + "");
		}
		inserts.deleteCharAt(0);
		if (primaryKeyId.indexOf(",") == -1) {
			if (Validator.isNotNull(String.valueOf(ids))) {
				ids.deleteCharAt(0);
				setObjIds(paramVo, ids.toString(), primaryKeyId);
			}
		} else {
			String str[] = primaryKeyId.split(",");
			for (int i = 0; i < str.length; i++) {
				setObjIds(paramVo, pkIds.get(str[i]).substring(1), str[i]);
			}
		}
		//saveLog(params, paramVo, "save", tableName);//记录日志
		return inserts.toString();
	}

	/**
	 * description:  拼动态原生的删除语句
	 */
	public String getDealSqlStr(Map<String, String> params, String attrStr, String tableName, ParamsVo paramVo,
			String primaryKeyId) {
		if (Validator.isEmpty(params) || params.size() <= 0)
			return "";
		StringBuilder sb2 = new StringBuilder("");
		boolean mark1 = false;
		String idValue = "";
		String rules = String.valueOf(paramVo.getParams("exe_rules"));//规则
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));//模型名,如：trpPub
		String dataSource = String.valueOf(paramVo.getParams("datasource"));
		Map<String, String> tableMap = getTableMap(model, dataSource);
		for (String key : params.keySet()) {
			/*String keyStr = key.substring(2);
			if (key.startsWith("wl_") || key.startsWith("wi_") || key.startsWith("wn_") || key.startsWith("wb_")) {
				keyStr = key.substring(3);
			}*/
			String clms[] = key.split("_");
			String keyStr = clms[clms.length-1];
			String val = params.get(key);
			if (attrStr.indexOf(keyStr) != -1 && clms.length >1) {
				String cloumn = upperCharToUnderLine(keyStr);
				if (val.startsWith("[")) {
					val = getValue(rules, model, keyStr, val);//从规则中获取值
				} else {
					rules = rules.replaceAll("\\[" + model + "." + keyStr + "\\]", val);//替换规则中的值
				}
				if (cloumn.equals(primaryKeyId)) {
					idValue = val;
				} else {
					if (primaryKeyId.indexOf(cloumn) != -1) {//联合主键
						setObjIds(paramVo, val, cloumn);
					}
				}
				if (Validator.isNull(val)) {
					continue;
				}
				//String whereSql = getWhereSql(tableMap, key, val, keyStr);
				String cm = key.replace("_" + keyStr, "_");
				String clomun = upperCharToUnderLine(keyStr);
				String whereSql = switchWhere(clomun, "", keyStr, val, tableMap, cm, dataSource);
				if (StrUtil.isNotNull(whereSql)) {
					sb2.append(whereSql);
					mark1 = true;
				}
			}
		}
		String iusWhere = String.valueOf(paramVo.getParams("ius_sql_where"));
		if(Validator.isNotNull(iusWhere)){//json拼的条件
			sb2.append(iusWhere);
			mark1 = true;
		}
		if (!mark1)
			return "";
		if (Validator.isNotNull(idValue) && primaryKeyId.indexOf(",") == -1) {
			params.put(toCamelNamed(primaryKeyId), idValue);
			setObjIds(paramVo, idValue, primaryKeyId);
		}

		String whereStr = sb2.toString();
		if (attrStr.indexOf("fsId") != -1) {
			String sql = "select fs_id from " + tableName + " where 1=1 " + whereStr;
			paramVo.setParams(paramVo.getParams("rulePrimaryKey") + "_sql", sql);
		}
		paramVo.setParams("exe_rules", rules);

		saveLog(params, paramVo, "delete", tableName);//记录日志
		return "delete from " + tableName + " where 1=1 " + whereStr;
	}

	/**
	 * description:  拼动态原生的修改语句
	 */
	public String getSelectSqlStr(Map<String, String> params, String attrStr, String tableName, ParamsVo paramVo,
			String primaryKeyId) {
		String orderBy = Validator.getDefaultStr(String.valueOf(paramVo.getParams("orderBy")), "");
		if (Validator.isNotNull(orderBy))
			orderBy = " order by " + orderBy;
		String rules = String.valueOf(paramVo.getParams("exe_rules"));
		String model = String.valueOf(paramVo.getParams("rulePrimaryKey"));
		String dataSource = String.valueOf(paramVo.getParams("datasource"));
		String iusWhere = String.valueOf(paramVo.getParams("ius_sql_where"));
		Map<String, String> tableMap = getTableMap(model, dataSource);
		if (Validator.isNull(rules)) {
			String sql = "select * from " + tableName + " where 1=1 ";
			if (Validator.isEmpty(params) || params.size() <= 0) {
				//
			} else {
				StringBuilder sb = new StringBuilder();
				for (String key : params.keySet()) {
					//String keyVal = key.substring(2);
					String clms[] = key.split("_");
					String keyVal = clms[clms.length-1];
//					if (key.startsWith("wl_") || key.startsWith("wi_") || key.startsWith("wn_")
//							|| key.startsWith("wb_")) {
//						keyVal = key.substring(3);
//					}
					if (attrStr.indexOf(keyVal) != -1) {
						String value = params.get(key);
						//sb.append(getWhereSql(tableMap, key, value, keyVal));
						String cm = key.replace("_" + keyVal, "_");
						String clomun = upperCharToUnderLine(keyVal);
						sb.append(switchWhere(clomun, "", keyVal, value, tableMap, cm, dataSource));
					}
				}
				if(Validator.isNotNull(iusWhere)){//json拼的条件
					sb.append(iusWhere);
				}
				sql += sb.toString();
			}
			return sql + " " + orderBy;
		}

		StringBuilder sb3 = new StringBuilder("");
		boolean mark2 = false;
		for (String key : params.keySet()) {
			String val = params.get(key);
			String clms[] = key.split("_");
			String keyStr = clms[clms.length-1];
//			if (key.startsWith("wl_") || key.startsWith("wi_") || key.startsWith("wn_") || key.startsWith("wb_")) {
//				keyStr = key.substring(3);
//			}
			if (val.startsWith("[")) {
				val = getValue(rules, model, keyStr, val);
			}
			if (attrStr.indexOf(keyStr) != -1) {
				//sb3.append(getWhereSql(tableMap, key, val, keyStr));
				String cm = key.replace("_" + keyStr, "_");
				String clomun = upperCharToUnderLine(keyStr);
				sb3.append(switchWhere(clomun, "", keyStr, val, tableMap, cm, dataSource));
				mark2 = true;
			}
		}
		if(Validator.isNotNull(iusWhere)){//json拼的条件
			sb3.append(iusWhere);
			mark2 = true;
		}
		if (!mark2) {
			return "";
		}
		return "select * from " + tableName + " where 1=1 " + sb3.toString() + " " + orderBy;
	}

	/**
	 * description:  拼动态原生的修改语句
	 */
	public String getSelectMoreSqlStr(ParamsVo vo, String models[], String sign) {
		String colmuns = String.valueOf(vo.getParams("result_column"));
		StringBuilder sbc = new StringBuilder("");
		StringBuilder sbw = new StringBuilder("");
		StringBuilder sbt = new StringBuilder("");

		boolean mark = Validator.isNotNull(colmuns) ? true : false;
		if (mark) {
			String model[] = colmuns.split(",");
			for (int q = 0; q < model.length; q++) {
				String objName = model[q].substring(0, model[q].indexOf('.'));
				String clomun = upperCharToUnderLine(model[q].substring(model[q].indexOf('.')));
				if (Validator.isNull(clomun))
					continue;
				if (Validator.isNotNull(sign)) {
					sbc.append("," + objName + clomun + " as \"" + objName + sign + clomun.substring(1) + "\"");
				} else {
					sbc.append("," + objName + clomun);
				}
			}
		}
		int whereNum = 0;
		String dataSource = String.valueOf(vo.getParams("datasource"));
		for (int i = 0; i < models.length; i++) {
			String prefix = models[i].substring(2);
			String attr = ToolsUtil.getInstance().getValueByKey("custom-method.properties", "obj_" + prefix);
			if (Validator.isNull(attr))
				attr = densgerSql(vo, prefix);
			if (Validator.isNull(attr))
				continue;
			String attrStr[] = attr.split(";");
			sbt.append("," + attrStr[3] + " " + prefix);
			Map<String, String> tableMap = getTableMap(prefix, dataSource);
			String model[] = attrStr[1].split(",");
			for (int q = 0; q < model.length; q++) {
				String clomun = upperCharToUnderLine(model[q]);
				if (Validator.isNull(clomun))
					continue;
				if (!mark) {
					if (Validator.isNotNull(sign)) {
						sbc.append("," + prefix + "." + clomun + " as \"" + prefix + sign + clomun + "\"");
					} else {
						sbc.append("," + prefix + "." + clomun);
					}
				}
				String strs[] = findClomns(prefix + ".",model[q],vo.getParams().keySet());
				for(int m=0;m<strs.length;m++){//查询条件
					String valStr = String.valueOf(vo.getParams(strs[m]));
					if(StrUtil.isNotNull(valStr)) {
						whereNum += 1;
						String cm = strs[m].replace(prefix + ".", "").replace("_" + model[q], "_");
						sbw.append(switchWhere(clomun, prefix + ".", model[q], valStr, tableMap, cm, dataSource));
					}
				}
				//sbw.append(getSelectWhere(clomun, prefix, model, tableMap, vo, q));//查询条件
			}
		}
		if (sbc.length() > 0)
			sbc.deleteCharAt(0);
		if (sbt.length() <= 0) {
			return "";
		}
		sbt.deleteCharAt(0);
		String orderBy = Validator.getDefaultStr(String.valueOf(vo.getParams("orderBy")), "");
		if (Validator.isNotNull(orderBy))
			orderBy = "order by " + orderBy;
		String iusWhere = String.valueOf(vo.getParams("ius_sql_where"));
		if(Validator.isNotNull(iusWhere)){//json拼的条件
			sbw.append(iusWhere);
		}
		if(String.valueOf(sbw).contains(" or ") && String.valueOf(sbw).startsWith(" or") && whereNum == 1){
			return "select " + sbc.toString() + " from " + sbt.toString() + " where 1=2 " + sbw.toString() + " " + orderBy;
		}
		return "select " + sbc.toString() + " from " + sbt.toString() + " where 1=1 " + sbw.toString() + " " + orderBy;
	}

	/**
	 * description:  拼动态原生的修改语句
	 */
	public String getSelectJoinSqlStr(ParamsVo vo, String models[], String sign) {
		String colmuns = String.valueOf(vo.getParams("result_column"));
		StringBuilder sbc = new StringBuilder("");
		StringBuilder sbw = new StringBuilder("");
		StringBuilder sbt = new StringBuilder("");
		String modelTypes = String.valueOf(vo.getParams("modelTypes"));
		boolean mark = Validator.isNotNull(colmuns) ? true : false;
		if (mark) {
			String model[] = colmuns.split(",");
			for (int q = 0; q < model.length; q++) {
				String objName = model[q].substring(0, model[q].indexOf('.'));
				String clomun = upperCharToUnderLine(model[q].substring(model[q].indexOf('.')));
				if (Validator.isNull(clomun))
					continue;
				if (Validator.isNotNull(sign)) {
					sbc.append("," + objName + clomun + " as \"" + objName + sign + clomun.substring(1) + "\"");
				} else {
					sbc.append("," + objName + clomun);
				}
			}
		}
		String dataSource = String.valueOf(vo.getParams("datasource"));
		String onStr[] = new String[2];//只支持两个表联查
		for (int i = 0; i < models.length; i++) {
			String prefix = models[i].substring(2);
			String attr = ToolsUtil.getInstance().getValueByKey("custom-method.properties", "obj_" + prefix);
			if (Validator.isNull(attr))
				attr = densgerSql(vo, prefix);
			if (Validator.isNull(attr))
				continue;
			String attrStr[] = attr.split(";");
			sbt.append("#" + attrStr[3] + " " + prefix);
			Map<String, String> tableMap = getTableMap(prefix, dataSource);
			String model[] = attrStr[1].split(",");
			for (int q = 0; q < model.length; q++) {
				String clomun = upperCharToUnderLine(model[q]);
				if (Validator.isNull(clomun))
					continue;
				if (!mark) {
					if (Validator.isNotNull(sign)) {
						sbc.append("," + prefix + "." + clomun + " as \"" + prefix + sign + clomun + "\"");
					} else {
						sbc.append("," + prefix + "." + clomun);
					}
				}
				if (Validator.isNotNull(String.valueOf(vo.getParams(prefix + ".wj_" + model[q])))) {//组织on条件
					onStr[i] = prefix + "." + clomun;
				} else {
					String strs[] = findClomns(prefix + ".",model[q],vo.getParams().keySet());
					for(int m=0;m<strs.length;m++){//查询条件
						String valStr = String.valueOf(vo.getParams(strs[m]));
						if(StrUtil.isNotNull(valStr)) {
							String cm = strs[m].replace(prefix + ".", "").replace("_" + model[q], "_");
							sbw.append(switchWhere(clomun, prefix + ".", model[q], valStr, tableMap, cm, dataSource));
						}
					}
					//sbw.append(getSelectWhere(clomun, prefix, model, tableMap, vo, q));//查询条件
				}
			}
		}
		sbc.deleteCharAt(0);
		sbt.deleteCharAt(0);
		String tables = sbt.toString();
		if (modelTypes.startsWith("sl_")) {
			tables = tables.replace("#", " left join on " + onStr[0] + "=" + onStr[1]);
		} else if (modelTypes.startsWith("sr_")) {
			tables = tables.replace("#", " right join on " + onStr[0] + "=" + onStr[1]);
		} else if (modelTypes.startsWith("si_")) {
			tables = tables.replace("#", " inner join on " + onStr[0] + "=" + onStr[1]);
		}
		String orderBy = Validator.getDefaultStr(String.valueOf(vo.getParams("orderBy")), "");
		if (Validator.isNotNull(orderBy))
			orderBy = "order by " + orderBy;
		String iusWhere = String.valueOf(vo.getParams("ius_sql_where"));
		if(Validator.isNotNull(iusWhere)){//json拼的条件
			sbw.append(iusWhere);
		}
		return "select " + sbc.toString() + " from " + tables + " where 1=1 " + sbw.toString() + " " + orderBy;
	}

	public String densgerSql(ParamsVo vo, String prefix) {
		String sortCode = String.valueOf(vo.getParams("sortCode"));
		String tab = "";
		if (Validator.isNull(sortCode)) {
			tab = upperCharToUnderLine(prefix);
			if (tab.indexOf('_') == -1)
				return "";
			sortCode = tab.substring(tab.indexOf('_') + 1);
		}
		String sysName = String.valueOf(vo.getParams("datasource"));
		sysName = StrUtil.doNull(sysName, DynamicDataSource.getInstance().getDefaultDataSourceKey());
		String key = MessageUtil.getTableCacheKey(sortCode, sysName, "_tableAttr");//sortCode + "_tableAttr";
		String content = String.valueOf(SystemTools.getInstance().getCache("").getCacheObjectByKey(key));
		if (Validator.isNotNull(content))
			return content;
		List<PubMetadata> list = InfoReleaseCoreCleint.getInstance().getMetadatas(sortCode, sysName);
		if (null == list)
			return "";
		StringBuffer sb = new StringBuffer(sortCode + ";");
		String primaryKey = "";
		String primaryKeys = "";
		Map<String, String> cloumn = new HashMap<String, String>();
		for (PubMetadata pm : list) {
			if ("1".equals(pm.getDataRestrict())) {//处理主键
				primaryKey = pm.getDataShortName();
			} else if ("4".equals(pm.getDataRestrict())) {//联合主键
				primaryKeys += "," + pm.getDataShortName();
			}
			sb.append(pm.getDataAttr() + ",");
			cloumn.put(pm.getDataAttr(), pm.getDataType());
		}
		if (Validator.isNotNull(primaryKeys)) {
			primaryKeys = primaryKeys.substring(1);
		}
		primaryKey = Validator.getDefaultStr(primaryKey, primaryKeys);
		sb.append(";" + primaryKey + ";" + tab);
		SystemTools.getInstance().getCache("").createCacheObject(key, sb.toString());
		String key2 = MessageUtil.getTableCacheKey(sortCode, sysName, "_tableMaps");
		SystemTools.getInstance().getCache("").createCacheObject(key2, cloumn);
		return sb.toString();
	}

	/**
	 * 获取表字段信息
	 * @param prefix objName
	 */
	public Map<String, String> getTableMap(String prefix, String sysName) {
		sysName = StrUtil.doNull(sysName, "plateform");
		String tab = upperCharToUnderLine(prefix);
		if (tab.indexOf('_') == -1)
			return new HashMap<String, String>(1);
		String sortCode = tab.substring(tab.indexOf('_') + 1);
		Map<String, String> resultMap = (Map) SystemTools.getInstance().getCache("")
				.getCacheObjectByKey(MessageUtil.getTableCacheKey(sortCode, sysName, "_tableMaps"));
		if (null == resultMap) {
			resultMap = new HashMap<String, String>(1);
		}
		return resultMap;
	}

	/**
	 * 判断字段类型是否为字符串
	 */
	public String sqlWhere(String column, String value, String dataType, int sqlType,String operator) {
		operator = StrUtil.doNull(operator,"=");
		StringBuilder sql = new StringBuilder();
		switch (sqlType) {
		case 1://insert
			if (StrUtil.isNotNull(value)) {
				value = value.replaceAll("'", "''");//过滤sql注入
			}
			if ("1".equals(dataType) || "2".equals(dataType) || "3".equals(dataType)) {
				sql.append(value);
			} else {
				if ("6".equals(dataType) && StrUtil.isNull(value)) {//日期类型
					sql.append("null");
				} else {
					sql.append("'" + value + "'");
				}
			}
			break;
		case 2:
			if (StrUtil.isNotNull(value)) {
				value = injectionSql(value);//过滤sql注入
			}
			if ("1".equals(dataType) || "2".equals(dataType) || "3".equals(dataType)) {
				sql.append(column + operator + value);
			} else {
				sql.append(column + operator +"'" + value + "'");
			}
			break;
		case 3://修改
			if (StrUtil.isNotNull(value)) {
				value = value.replaceAll("'", "''");//过滤sql注入
			}
			if ("1".equals(dataType) || "2".equals(dataType) || "3".equals(dataType)) {
				sql.append(column + operator + value);
			} else {
				sql.append(column + operator +"'" + value + "'");
			}
			break;
		default:
			if (StrUtil.isNotNull(value)) {
				value = injectionSql(value);//过滤sql注入
			}
			if ("1".equals(dataType) || "2".equals(dataType) || "3".equals(dataType)) {
				sql.append(column + operator + value);
			} else {
				sql.append(column + operator + "'" + value + "'");
			}
		}
		return sql.toString();
	}

	/**
	 * 过滤sql注入
	 */
	private String injectionSql(String value) {
		if (StrUtil.isNull(value))
			return "";
		int count = value.indexOf(";");
		if (count != -1) {
			value = value.substring(0, count);
		}
		value = value.replaceAll("'", "''");//过滤sql注入
		//value = value.replaceAll(";", "\\\\;");//过滤sql注入
		//return value.replaceAll(".*([;]+|(--)+).*", " ");//过滤sql注入
		return value.replaceAll(".*((--)+).*", " ");//过滤sql注入
	}

	/**
	 * description:  组装对象参数
	 */
	private void setObjIds(ParamsVo vo, String objId, String primarkId) {
		String modelType = String.valueOf(vo.getParams("rulePrimaryKey"));
		Map<String, String> ids = (Map) vo.getParams("resultIds");
		if (Validator.isEmpty(ids)) {
			ids = new HashMap<String, String>();
		}
		if (primarkId.indexOf(",") == -1) {
			ids.put(modelType + "_" + toCamelNamed(primarkId), objId);
		} else {
			String str[] = primarkId.split(",");
			for (int i = 0; i < str.length; i++) {
				ids.put(modelType + "_" + toCamelNamed(str[i]), objId);
			}
		}
		vo.setParams("resultIds", ids);
	}

	private String getValue(String rules, String model, String attr, String val) {
		String attrName = model + "." + attr;
		if (val.startsWith("[")) {
			int ct = rules.indexOf(attrName + ":");
			if (ct > -1) {
				String str[] = rules.substring(ct).split(",");
				for (int i = 0; i < str.length; i++) {
					if (str[i].startsWith(attrName)) {
						return str[i].substring(attrName.length() + 1);
					}
				}
			}
		}
		return val;
	}

	/**
	 * description:  获取类中所有属性值
	 */
	protected String getReflectAttr(Object model) {
		StringBuilder sb = new StringBuilder("");
		Field[] field = model.getClass().getDeclaredFields(); //获取实体类的所有属性，返回Field数组  
		for (int j = 0; j < field.length; j++) { //遍历所有属性
			sb.append(field[j].getName() + ","); //获取属性的名字
		}
		return sb.toString();
	}

	/**
	 * description:  将类属性改成数据字段名
	 */
	protected String upperCharToUnderLine(String param) {
		Pattern p = Pattern.compile("[A-Z]");
		if (param == null || param.equals("")) {
			return "";
		}
		StringBuilder builder = new StringBuilder(param);
		Matcher mc = p.matcher(param);
		int i = 0;
		while (mc.find()) {
			builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
			i++;
		}
		if ('_' == builder.charAt(0)) {
			builder.deleteCharAt(0);
		}
		return builder.toString();
	}

	/**
	 * 添加日志信息
	 */
	@SuppressWarnings("unchecked")
	private void saveLog(Map logMap, ParamsVo paramVo, String logType, String className) {
		logMap.put("log_returnValue", "true");
		logMap.put("logType", logType);
		logMap.put("logClassName", toCamelNamed(className));
		logMap.put("logIp", String.valueOf(paramVo.getParams("logReqIp")));
		logMap.put("log_userEname", String.valueOf(paramVo.getParams("logOperatorUser")));
		LogWriteRunnable runable = new LogWriteRunnable(logMap);
		ScheduledExecutor.newInstance().saveLogger(runable);
	}

	/**
	 * 属性值生成,符合骆驼命名
	 */
	protected String toCamelNamed(String str) {
		String names[] = str.split("_");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < names.length; i++) {
			if (i == 0) {
				sb.append(names[i].toLowerCase());
			} else {
				sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}

	protected IusSqlPorxyPlugin getPlugin() {
		if (null == iusSqlPorxyPlugin) {
			iusSqlPorxyPlugin = (IusSqlPorxyPlugin) SpringContextLoader.getBean("iusSqlPorxyPlugin");
		}
		return iusSqlPorxyPlugin;
	}

	/**
	 * 获取插件缓存CacheManager
	 * @return
	 */
	protected CacheManager getPluginsCache() {
		return LoadCacheFactory.getInstance().getCacheManager(CustomMethodPlugin.pluginsCache);
	}

	private void setIusParamCache(String key, Map<String, String> params) {
		if (JedisSsoUtil.getInstance().isRedisCache()) {
			JedisSsoUtil.getInstance().setIusparamcache(key, params);
		} else {
			SystemTools.getInstance().getCache("iusparamcache").createCacheObject(key, params);
		}
	}

	private boolean isSysParamManager(String tableName, Map<String, String> params, List<Map<String, String>> list) {
		String objName = toCamelNamed(tableName.trim());
		if ("sysParamManager".equalsIgnoreCase(objName)) {
			if (null == params && null == list)
				return true;
			try {
				if (null != list && !list.isEmpty()) {
					for (int i = 0; i < list.size(); i++) {
						Map<String, String> ps = list.get(i);
						String key = ps.get("formName") + "_" + ps.get("pageName");
						setIusParamCache(key, ps);
					}
				} else {
					String key = params.get("formName") + "_" + params.get("pageName");
					setIusParamCache(key, params);
				}
			} catch (Exception e) {
				//
			}
		}
		return false;
	}

	private String switchWhere(String clomun, String objName, String clomunName,String value, Map<String, String> tableMap,String prefixKey,String datasource){
		// objName值为 objName+ "."
		String pk[] = prefixKey.split("_");
		String cond = " and ",prefix = pk[0]+"_";
		if(pk.length>1){
			cond = " "+pk[1]+" ";
		}
		switch (prefix){
			case "isn_"://为空
				return cond + objName + clomun +" is null";
			case "isnn_"://不为空
				return cond + objName + clomun +" is not null";
		}
		if(Validator.isNull(value)) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		switch (prefix){
			case "w_" ://等于
				sb.append(cond + sqlWhere(objName + clomun, value,tableMap.get(clomunName), 2,""));
				break;
			case "wo_" ://等于
				sb.append(" or " + sqlWhere(objName + clomun, value, tableMap.get(clomunName), 2,""));
				break;
			case "w!_"://不等于
				sb.append(cond + sqlWhere(objName + clomun, value,tableMap.get(clomunName), 2,"!="));
				break;
			case "wb_"://在...范围内
				String whs[] = value.split(",");
				sb.append(sqlCompare2(whs, objName +clomun, tableMap.get(clomunName),cond,"<=","<="));
				break;
			case "wb!_"://不在...范围内
				String wbs[] = value.split(",");
				String wbs2[] = new String[wbs.length];
				for(int i = 0; i < wbs2.length; i++) {
					wbs2[i] = wbs[wbs.length - i - 1];
				}
				sb.append(sqlCompare2(wbs2, objName +clomun, tableMap.get(clomunName),cond,"<=","<="));
				break;
			case "wgt_"://大于
				String wgt[] = {value};
				sb.append(sqlCompare2(wgt, objName +clomun, tableMap.get(clomunName),cond,">",""));
				break;
			case "wgteq_"://大于等于
				String wgteq[] = {value};
				sb.append(sqlCompare2(wgteq, objName +clomun, tableMap.get(clomunName),cond,">=",""));
				break;
			case "wi_"://包含 in()
				sb.append(cond + objName + clomun + " in(" + StrUtil.strArrayToStr(value.split(","), ",", "'") + ")");
				break;
			case "wl_"://like查询
				String val = value.replaceAll(".*((--)+).*", " ").replaceAll("'", "''");
				if (!" ".equals(val))
					sb.append(cond + objName + clomun + " like '%" + val + "%'");
				break;
			case "wlt_"://小于
				String wlt[] ={"-",value};
				sb.append(sqlCompare2(wlt, objName +clomun, tableMap.get(clomunName),cond,"","<"));
				break;
			case "wlteq_"://小于等于
				String wlteq[] ={"-",value};
				sb.append(sqlCompare2(wlteq, objName +clomun, tableMap.get(clomunName),cond,"","<="));
				break;
			case "wn_":// not in
				sb.append(cond + objName + clomun + " not in(" + StrUtil.strArrayToStr(value.split(","), ",", "'") + ")");
				break;
			case "wc_"://包含
				String dataType = ConnctionData.getInstance().getDataBaseType(null, "", datasource);
				if ("oracle".equals(dataType)) {
					sb.append(cond+" instr(','||" + objName + clomun + "||',',','||'" + value + "'||',')>0");
				} else if ("mysql".equals(dataType)) {
					sb.append(cond+" instr(concat(','," + objName + clomun + ",','),concat(',','" + value + "',','))>0");
				}
				break;
			default:
				if (value.startsWith("[")) {//解析关系：pub.proId=[pro.proId]
					value = value.replace("[", "").replace("]", "");
					sb.append(cond + objName + clomun + "=" + value.substring(0, value.indexOf('.'))
							+ upperCharToUnderLine(value.substring(value.indexOf('.'))) + "");
				} else {
					sb.append(cond + sqlWhere(objName + clomun, value, tableMap.get(clomunName), 2,""));
				}
		}
		return sb.toString();
	}

	private String sqlCompare2(String whs[], String clomun, String dataType,String cond,String oper1,String oper2) {
		StringBuilder sql = new StringBuilder();
		if ("1".equals(dataType) || "2".equals(dataType) || "3".equals(dataType)) {//数字型
			if (whs.length > 1) {
				if (whs[0].equals("-")) {//不比较开始值用'-'表示
					sql.append(cond + clomun + oper2 + whs[1]);
				} else {
					sql.append(cond + "("+whs[0] + oper1 + clomun + " and " + clomun + oper2 + whs[1]+")");
				}
			} else {
				sql.append(cond + clomun + oper1 + whs[0]);
			}
		} else {//字符型
			if (whs.length > 1) {
				if (whs[0].equals("-")) {//不比较开始值用'-'表示
					sql.append(cond + clomun + oper2+"'" + whs[1] + "'");
				} else {
					sql.append(cond+ " ('" + whs[0] + "'"+oper1 + clomun + " and " + clomun +oper2+ "'" + whs[1] + "')");
				}
			} else {
				sql.append(cond + clomun + oper1+"'" + whs[0] + "'");
			}
		}
		return sql.toString();
	}

	private String[] findClomns(String objName, String attr, Set<String> keys){
		StringBuilder str = new StringBuilder();
		for(String key : keys){
			if(key.endsWith("_"+attr) && key.startsWith(objName)){
				str.append(","+key);
			}
		}
		if(str.length()>1) {
			str.deleteCharAt(0);
		} else {
			str.append(objName+attr);
		}
		return str.toString().split(",");
	}
}
